<?php
// +----------------------------------------------------------------------
// | RXThinkCMF框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2020 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: 牧羊人 <1175401194@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\service\OfPatentService;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\View;

/**
 * 专利管理-控制器
 * @author 牧羊人
 * @since: 2021/12/24
 * Class Ofpatent
 * @package app\admin\controller
 */
class Ofpatent extends Backend
{
    /**
     * 初始化方法
     * @author 牧羊人
     * @since: 2021/12/24
     */
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model            = new \app\admin\model\OfPatent();
        $this->service          = new OfpatentService();
        $this->OfcompanyService = new \app\admin\service\OfCompanyService();
        $this->Ofcontract       = new \app\admin\model\OfContract();
        $this->OfCompanyModel   = new \app\admin\model\OfCompany();
        $this->adminModel       = new \app\admin\model\Admin();
        $this->OfcompanyService = new \app\admin\service\OfCompanyService();
    }

    /**
     * 数据列表页
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function index()
    {
        $company_id = input("company_id", 0);
        // 客户列表
        $companyMod  = new \app\admin\model\OfCompany();
        $companyList = $companyMod->where("mark", 1)->order("id desc")->select()->toArray();
        View::assign("companyList", $companyList);
        // 合同列表
        $contractMod  = new \app\admin\model\OfContract();
        $contractList = $contractMod->where("mark", 1)->order("id desc")->select()->toArray();
        View::assign("contractList", $contractList);

        View::assign("company_id", $company_id);
        $statusList = config('admin.patentnotice_status');
        View::assign("statusList", $statusList);

        $newstatusList = config('admin.patentnotice_status_2');
        View::assign("newstatusList", $newstatusList);

        $patent_type    = config('admin.patent_type');
        $patent_an_type = config('admin.patent_an_type');
        if (IS_POST) {
            $result = $this->service->getList();
            foreach ($result['data'] as $key => &$value) {
                $result['data'][$key]['new_status_text'] = $newstatusList[$value['new_status']];
                $result['data'][$key]['patent_type']     = $patent_type[$value['patent_type']];
                $result['data'][$key]['type']            = $patent_an_type[$value['type']];

                $agent_id_str                        = Db::name("admin")->where("id", 'in', $value['agent_id'])->column("realname");
                if($agent_id_str){
                    $agent_id_str = implode('、', $agent_id_str);
                }else{
                    $agent_id_str = '';
                }
                $result['data'][$key]['agent_id']    = $agent_id_str;
                $result['data'][$key]['conveyancer'] = Db::name("admin")->where("id", $value['conveyancer'])->value("username");

                $dao = 0;
                //答复绝限减去今日 得出倒计时  如果绝限大于今日才减
                $time1 = strtotime($value['reply_limit']);
                if($time1){
                    $time2 = time();
                    if($time1 > $time2){
                        $dao  = ceil(($time1-$time2)/86400);
                    }
                }
                
                $result['data'][$key]['dao'] = $dao;

            }
            return $result;
        }
        // 取消模板布局
        $this->app->view->layout(false);
        // 默认参数
        $data = func_get_args();
        if (isset($data[0])) {
            foreach ($data[0] as $key => $val) {
                View::assign($key, $val);
            }
        }
        return $this->render();
    }

    /**
     * 批量添加数据列表页
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function add_list()
    {
        if (IS_POST) {
            $param = request()->param();
            $rs    = 0;
            if (!empty($param)) {
                $company_id    = $param['company_id'];
                $contract_id   = $param['contract_id'];
                $patent_name   = $param['patent_name'];
                $patent_type   = $param['patent_type'];
                $remark        = $param['remark'];
                $inside_number = $param['inside_number'];
                $datas         = [];
                foreach ($patent_name as $key => $value) {
                    $data                  = [];
                    $data['company_id']    = $company_id;
                    $data['contract_id']   = $contract_id;
                    $data['patent_name']   = $value;
                    $data['patent_type']   = $patent_type[$key];
                    $data['remark']        = $remark[$key];
                    $data['inside_number'] = $inside_number[$key];
                    $data['create_time']   = time();
                    $datas[]               = $data;
                }
                $rs = Db::name("of_patent")->insertAll($datas);
            }
            if ($rs) {
                return message("添加成功", true);
            } else {
                return message("添加成功", false);
            }
        }
        return $this->render();
    }

    /**
     * 添加或编辑
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author 牧羊人
     * @since 2020/7/2
     */
    public function edit()
    {
        if (IS_POST) {
            $id     = input("id", 0);
            $status = input("status", '');

            $inside_number = input('inside_number', '');
            if ($inside_number) {
                $check_inside_number = $this->model->where('mark', 1)->where('id', '<>', $id)->where('inside_number', $inside_number)->value('id');
                if ($check_inside_number) {
                    return message('内部编号不能重复', false);
                }
            }
            $pay_year = input('pay_year/int', 1);
            if ($pay_year < 1) {
                return message('第N年必须是数字且不能小于1', false);
            }
            $company_id = input('company_id', '');
            if (!$company_id) {
                return message('请选择正确的客户', false);
            }

            $result = $this->service->edit();
            // if ($status == 2 && $result['code'] == 0) {
            //     $moni = new \app\admin\service\OfPatentMonitorService();
            //     $moni->monitor($id);
            // }
            return $result;
        }
        // 客户列表
        $companyMod = new \app\admin\model\OfCompany();
        $list       = $companyMod->where("mark", 1)->order("id desc")->select()->toArray();
        View::assign("list", $list);

        $info         = [];
        $id           = input("get.id", 0);
        $contractInfo = "";
        if ($id) {
            $info = $this->model->getInfo($id);
            if (!empty($info['contract_id'])) {
                $contractInfo = Db::name("of_contract")->where("id", $info['contract_id'])->find();
            }
        } else {
            $info['agent_id'] = '';
            $data = func_get_args();
            if (isset($data[0])) {
                foreach ($data[0] as $key => $val) {
                    $info[$key] = $val;
                }
            }
        }

        View::assign("contractInfo", $contractInfo);
        View::assign("info", $info);
        $statusList = config('admin.patentnotice_status');
        View::assign("statusList", $statusList);
        $newStatusList = config('admin.patentnotice_status_2');
        View::assign('newStatusList', $newStatusList);
        $patent_type = config('admin.patent_type');
        if (isset($patent_type[0])) {
            unset($patent_type[0]);
        }
        View::assign("patent_type", $patent_type);
        $patent_an_type = config('admin.patent_an_type');
        View::assign("patent_an_type", $patent_an_type);

        $adminMod = new \app\admin\model\Admin();
        // 代理人列表
        $wh            = [];
        $wh[]          = ['mark', '=', 1];
        $wh[]          = ['role_ids', 'like', "%4%"];
        $agentList     = $adminMod->where($wh)->select()->toArray();
        $new_agentList = [];
        foreach ($agentList as $key => $value) {
            $tmp = [
                'name'  => $value['realname'],
                'value' => $value['id'],
            ];
            $new_agentList[] = $tmp;
        }

        View::assign("agentList", $new_agentList);

        // 撰写人列表
        $whereOr1 = [
            ['role_ids', 'like', "%8%"],
            ['mark', '=', 1],
        ];
        $whereOr2 = [
            ['role_ids', 'like', "%4%"],
            ['mark', '=', 1],
        ];
        $conveyancerList = $adminMod->whereOr([$whereOr1, $whereOr2])->select()->toArray();
        View::assign("conveyancerList", $conveyancerList);
        return $this->render();
    }

    /**
     * 缴费操作
     */
    public function exeUpdate()
    {
        $ids  = input("ids", 0);
        $type = input("type", 0);
        $msg  = message("执行失败", false);
        $rs   = true;
        if ($type == 1) {
            $wh   = [];
            $wh[] = ['id', 'in', $ids];
            $list = Db::name("of_patent")->where($wh)->select();
            if (!empty($list)) {
                foreach ($list as $key => $value) {
                    if ($value['issue_date']) {
                        $year             = $value['pay_year'];
                        $data             = [];
                        $data['pay_year'] = $year + 1;

                        $issue_time           = strtotime($value['issue_date']);
                        $data['payment_date'] = date('Y-m-d', strtotime("+$year year", $issue_time));
                        Db::name("of_patent")->where('id', 'in', $value['id'])->update($data);
                    }

                }
            }
        }
        if ($rs) {
            $msg = message("执行成功", true);
        }
        return json_encode($msg);
    }

    /**
     * 批量添加数据列表页
     * https://blog.csdn.net/lmy1998/article/details/118420437 参考此处 原先导入的模式 因为7.4的原因语法报错
     * @return mixed
     * @since 2020/7/5
     * @author 牧羊人
     */
    public function batch_import()
    {
        if (IS_POST) {
            $param = request()->param();
            $data  = $this->getUrl($param['url']);
            if (!$data) {
                return message();
            }
            return message($data, false);
        } else {
            return $this->render();
        }

    }

    /**
     * 客户必填 合同编号必填
     * 查重
     * 不能为空
     * 如果错误则不让导入
     */
    public function getUrl($path)
    {
        ini_set('max_execution_time', '0');
        $msg = '';

        $file = 'uploads/' . $path;
        if (!is_file($file)) {
            return "\n 请选择文件";
        }
        $data = $this->OfcompanyService->readFile($file, 1);
        if (!$data) {
            $msg .= "\n 没有可导入的数据,请确认导入的文件正确";
            return $msg;
        }

        $save_data = [];
        foreach ($data as $k => $item) {
            //判断模板是否正确
            if ($k == 1) {
                if ($item[0] !== '最新状态' || $item[1] !== '期限截止日' || $item[11] !== '专利名称') {
                    $msg .= "\n 模板错误请选择正确的模板进行导入";
                    return $msg;
                }
                continue;
            }
            //跳过空行
            $is_empty = '';
            foreach ($item as $key => $value) {
                $is_empty .= $value;
            }
            if (!$is_empty) {
                continue;
            }
            if (empty($item[5])) {
                $msg .= "\n" . $k . "行:客户名称未填写";
                return $msg;
            }
            // if (empty($item[11])) {
            //     $msg .= "\n" . $k . "行:专利名称未填写";
            //     return $msg;
            // }
            //客户名称必填 且需要查询出id
            $company_id = $this->OfCompanyModel->where('name', $item[5])->where('mark', 1)->value('id');
            if (!$company_id) {
                $msg .= "\n" . $k . "行:客户未匹配";
                return $msg;
            }
            //最新模板未见合同字段
            $contract_id = 0;
            // if ($item[3]) {
            //     $contract_id = $this->Ofcontract->where('contract_no', $item[3])->where('mark', 1)->value('id');
            //     if (!$contract_id) {
            //         $msg .= "\n" . $k . "行:合同编号未匹配到合同";
            //         return $msg;
            //     }
            // }
            //代理人 需要查询出id
            $agent_id = '';
            if ($item[15]) {
                $agent_id_str = explode('、', $item[15]);
                foreach ($agent_id_str as $agent_tmp) {
                    $agent_tmp_id = $this->adminModel->where('realname', $agent_tmp)->where('mark', 1)->value('id');
                    if (!$agent_tmp_id) {
                        $msg .= "\n" . $k . "行:代理人未匹配";
                        return $msg;
                    }
                    $agent_id .= $agent_tmp_id . ',';
                }

            }
            //conveyancer 撰写人
            $conveyancer = 0;
            if ($item[16]) {
                $conveyancer = $this->adminModel->where('realname', $item[16])->where('mark', 1)->value('id');
                if (!$conveyancer) {
                    $msg .= "\n" . $k . "行:撰写人未匹配";
                    return $msg;
                }
            }

            $status = 0;
            if ($item[0]) {
                $statusList = config('admin.patentnotice_status_2');
                if (!in_array($item[0], $statusList)) {
                    $msg .= "\n" . $k . "行:最新状态错误";
                    return $msg;
                }
                foreach ($statusList as $key => $value) {
                    if ($item[0] == $value) {
                        $status = $key;
                    }
                }
            }
            $patent_type = 0;
            if ($item[9]) {
                $patent_type = config('admin.patent_type');
                if (!in_array($item[9], $patent_type)) {
                    $msg .= "\n" . $k . "行:专利类型填写错误";
                    return $msg;
                }
                foreach ($patent_type as $key => $value) {
                    if ($item[9] == $value) {
                        $patent_type = $key;
                    }
                }
            }

            $type = 0;
            if ($item[8]) {
                $patent_an_type = config('admin.patent_an_type');
                if (!in_array($item[8], $patent_an_type)) {
                    $msg .= "\n" . $k . "行:案件类型填写错误";
                    return $msg;
                }
                foreach ($patent_an_type as $key => $value) {
                    if ($item[8] == $value) {
                        $type = $key;
                    }
                }
            }

            $item1  = $this->OfcompanyService->changDate($item[1]); //期限截止日
            $item2  = $this->OfcompanyService->changDate($item[2]); //案件状态更新日
            $item13 = $this->OfcompanyService->changDate($item[13]); //申请日
            $item22 = $this->OfcompanyService->changDate($item[22]); //答复绝限
            $item23 = $this->OfcompanyService->changDate($item[23]); //公告日
            // //查重 专利名称+客户
            // $map = [
            //     ['mark', '=', 1],
            //     ['company_id', '=', $company_id],
            //     ['patent_name', '=', $item[11]],
            // ];

            // //优先查重表格
            // $excel_map = [
            //     ['company_id' => $company_id],
            //     ['patent_name' => $item[11]],
            // ];
            // $is_excel_set = $this->OfcompanyService->checkDuplicate($excel_map, $save_data);
            // if ($is_excel_set) {
            //     $msg .= "\n" . $k . "行:重复(当前导入的表格中存在相同客户与专利名称)";
            //     return $msg;
            // }

            // $is_set = $this->model->where($map)->value('id');
            // if ($is_set) {
            //     $msg .= "\n" . $k . "行:重复(数据库中存在相同客户与专利名称)";
            //     return $msg;
            // }

            $save_data[] = [
                'new_status'          => $status,
                'end_date'            => $item1,
                'update'              => $item2,
                'remark'              => $item[3],
                'subsidy'             => $item[4],
                'company_id'          => $company_id,
                'number'              => $item[6],
                'country'             => $item[7],
                'type'                => $type,
                'patent_type'         => $patent_type,
                'applicant'           => $item[10],
                'patent_name'         => $item[11],
                'application_number'  => $item[12],
                'apply_date'          => $item13,
                'relation_number'     => $item[14],
                'agent_id'            => $agent_id,
                'conveyancer'         => $conveyancer,
                'cartographer'        => $item[17],
                'inventor'            => $item[18],
                'first_inventor_id'   => $item[19],
                'fee_reduction_ratio' => $item[20],
                'application_fee'     => $item[21],
                'reply_limit'         => $item22,
                'announcement_date'   => $item23,

                'contract_id'         => $contract_id,
                'create_time'         => time(),
                'update_time'         => time(),
            ];
        }
        if (!$save_data) {
            $msg .= "\n 没有可导入的数据,请确认导入的文件正确";
            return $msg;
        }

        $res = $this->model->saveAll($save_data);
        if ($res) {
            $msg .= "";
        } else {
            $msg .= "\n 插入未知错误";
        }
        return $msg;
    }

    public function download()
    {
        ini_set('max_execution_time', '0');
        $param = request()->param();
        // 查询要导出的数据
        $map = [
            ['mark', '=', 1],
        ];
        if ($param['number']) {
            $map[] = ['number', 'like', '%' . $param['number'] . '%'];
        }
        if ($param['application_number']) {
            $map[] = ['application_number', 'like', '%' . $param['application_number'] . '%'];
        }
        if ($param['new_status']) {
            $map[] = ['new_status', '=', $param['new_status']];
        }
        // 客户名称
        if ($param['company_id']) {
            $map[] = ['company_id', '=', $param['company_id']];
        } else {
            $admin_id = session("adminId");
            if ($admin_id != 1) {
                $wh_or   = [];
                $wh_or[] = ["service_id", "=", $admin_id];
                $wh_or[] = ["agent_id", "=", $admin_id];
                $wh_or[] = ["peer_id", "=", $admin_id];
                $arr_ids = Db::name("of_company")->where('mark', 1)->where(function ($query) use ($wh_or) {$query->whereOr($wh_or);})->column("id");
                if (!empty($arr_ids)) {
                    $map[] = ['company_id', 'in', $arr_ids];
                }
            }
        }

        $head = [
            ['title' => '最新状态', 'width' => 50],
            ['title' => '期限截止日', 'width' => 50],
            ['title' => '案件状态更新日', 'width' => 15],
            ['title' => '特别交代事项', 'width' => 15],
            ['title' => '补助', 'width' => 15],
            ['title' => '客户名称', 'width' => 20],
            ['title' => '案件号', 'width' => 50],
            ['title' => '国家', 'width' => 15],
            ['title' => '案件类型', 'width' => 15],
            ['title' => '专利类型', 'width' => 50],
            ['title' => '申请人', 'width' => 50],
            ['title' => '专利名称', 'width' => 50],
            ['title' => '申请号', 'width' => 15],
            ['title' => '申请日', 'width' => 15],
            ['title' => '同日申请关联卷号', 'width' => 15],
            ['title' => '案件代理人', 'width' => 20],
            ['title' => '专利撰写人', 'width' => 50],
            ['title' => '制图员', 'width' => 15],
            ['title' => '发明人', 'width' => 15],
            ['title' => '第一发明人ID', 'width' => 50],
            ['title' => '费减比例', 'width' => 50],
            ['title' => '申请费', 'width' => 50],
            ['title' => '答复绝限', 'width' => 50],
            ['title' => '公告日', 'width' => 50],
        ];

        $data = $this->model->where($map)->order('id desc')->select();

        $new_data = [];
        foreach ($data as $key => $v) {
            $tmp = [];
            //最新状态
            $statusList = config('admin.patentnotice_status_2');
            $new_status = $statusList[$v['new_status']];
            //案件类型
            $patent_an_type = config('admin.patent_an_type');
            $type           = $patent_an_type[$v['type']];
            //专利类型
            $patent_type_list = config('admin.patent_type');
            $patent_type      = $patent_type_list[$v['patent_type']];
            //客户名称
            $company_namem = Db::name("of_company")->where("id", $v['company_id'])->value('name');
            //代理
            $agent = Db::name("admin")->where("id", 'in', $v['agent_id'])->column('realname');
            $agent = implode('、', $agent);
            //撰写人
            $conveyancer = Db::name("admin")->where("id", $v['conveyancer'])->value('realname');

            $tmp[] = $new_status;
            $tmp[] = $v['end_date'];
            $tmp[] = $v['update'];
            $tmp[] = $v['remark'];
            $tmp[] = $v['subsidy'];
            $tmp[] = $company_namem;
            $tmp[] = $v['number'];
            $tmp[] = $v['country'];
            $tmp[] = $type;
            $tmp[] = $patent_type;
            $tmp[] = $v['applicant'];
            $tmp[] = $v['patent_name'];
            $tmp[] = $v['application_number'];
            $tmp[] = $v['apply_date'];
            $tmp[] = $v['relation_number'];
            $tmp[] = $agent;
            $tmp[] = $conveyancer;
            $tmp[] = $v['cartographer'];
            $tmp[] = $v['inventor'];
            $tmp[] = $v['first_inventor_id'];
            $tmp[] = $v['fee_reduction_ratio'];
            $tmp[] = $v['application_fee'];
            $tmp[] = $v['reply_limit'];
            $tmp[] = $v['announcement_date'];

            $new_data[] = $tmp;
        }
        $fileName = '专利(' . date("Y-m-d H:i:s") . ')';
        $this->OfcompanyService->exportExcel($head, $new_data, $fileName);
    }

}
